<template>
  <div class="guest">
    <van-nav-bar title="新用户登记" fixed placeholder>
      <template #left>
        <van-uploader :after-read="afterRead">身份证识别</van-uploader>
      </template>
      <template #right>
        <div v-if="submitDis" class="btn" @click="submit">提交</div>
      </template>
    </van-nav-bar>

    <van-form label-width="35%" ref="formCom">
      <van-field
        label="姓名"
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
        v-model="form.name"
        required
      ></van-field>
      <van-field
        label="性别"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      >
        <template #input>
          <van-radio-group v-model="form.gender" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        label="生日"
        v-model="form.birthday"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      ></van-field>
      <van-field
        label="民族"
        v-model="form.ethnicity"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      ></van-field>
      <van-field
        label="身份证号"
        v-model="form.idNumber"
        name="idNumber"
        required
        :rules="[
          { required: true, message: '必填', trigger: 'onChange' },
          {
            pattern:
              /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
            message: '请正确输入身份证号',
            trigger: 'onChange'
          }
        ]"
      ></van-field>
      <van-field
        label="地址"
        v-model="form.address"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      ></van-field>
      <van-field
        label="电话号码"
        v-model.trim="form.telephone"
        required
        :rules="[
          { required: true, message: '必填', trigger: 'onChange' },
          {
            pattern: /^1[0-9][0-9]{9}$/,
            message: '请正确输入手机号',
            trigger: 'onChange'
          }
        ]"
      ></van-field>
      <van-field label="班级">
        <template #input>
          <div>
            <van-button @click="classClick" type="primary" size="mini"
              >选择班级</van-button
            >
            <!-- <van-button
              type="danger"
              size="mini"
              @click="setClass('其它待定班级')"
            >
              其它待定班级</van-button
            > -->
            <div class="tclass">
              {{ className }}
            </div>
          </div>
        </template>
      </van-field>
      <van-field
        label="紧急联系人"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
        v-model="form.emergencyContact"
      ></van-field>
      <van-field
        label="紧急联系人电话"
        :rules="[
          { required: true, message: '必填', trigger: 'onChange' },
          {
            pattern: /^1[0-9][0-9]{9}$/,
            message: '请正确输入手机号',
            trigger: 'onChange'
          }
        ]"
        v-model.trim="form.emergencyContactTel"
        required
      ></van-field>
      <!-- <van-field label="疫苗接种情况">
        <template #input>
          <van-radio-group v-model="form.cov19">
            <van-radio class="mb10" :name="0">未接种</van-radio>
            <van-radio class="mb10" :name="1">接种一针</van-radio>
            <van-radio class="mb10" :name="2">接种二针</van-radio>
            <van-radio class="mb10" :name="3">接种三针</van-radio>
          </van-radio-group>
        </template>
      </van-field> -->
      <van-field label="用户特征">
        <template #input>
          <van-checkbox-group v-model="other" @change="changeOther">
            <van-checkbox class="mb10" name="isSmoke">吸烟</van-checkbox>
            <van-checkbox class="mb10" name="isSnore">打呼噜</van-checkbox>
            <van-checkbox class="mb10" name="isGame">沉迷游戏</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <van-field
        label="头像"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      >
        <template #input>
          <van-uploader
            :after-read="uploadAvatar"
            v-model="avatarImg"
            :max-count="1"
          />
        </template>
      </van-field>
      <van-field
        label="身份证复印件"
        required
        :rules="[{ required: true, message: '必填', trigger: 'onChange' }]"
      >
        <template #input>
          <van-uploader
            :after-read="uploadCard"
            :max-count="1"
            v-model="cardImg"
          >
          </van-uploader>
        </template>
      </van-field>
    </van-form>

    <!-- <van-cell-group>
      <van-cell title="姓名" :value="userInfo['姓名']?.words"></van-cell>
      <van-cell title="性别" :value="userInfo['性别']?.words"></van-cell>
      <van-cell title="民族" :value="userInfo['民族']?.words"></van-cell>
      <van-cell title="住址" :value="userInfo['住址']?.words"></van-cell>
      <van-cell title="生日" :value="userInfo['出生']?.words"></van-cell>
      <van-cell
        title="公民身份号码"
        :value="userInfo['公民身份号码']?.words"
      ></van-cell>
    </van-cell-group> -->
    <ClassPopup ref="classPopup" @setClass="setClass"></ClassPopup>
  </div>
</template>

<script setup>
import { getAccessToken, guestAdd, checkIdNumber } from '@/api/index'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import ClassPopup from './components/classPopup.vue'
import { Toast, Dialog } from 'vant'
const className = ref('')
const form = ref({
  name: '',
  gender: 0,
  birthday: '',
  ethnicity: '',
  idNumber: '',
  address: '',
  telephone: '',
  avatar: '',
  idCardImage: '',
  emergencyContact: '',
  emergencyContactTel: '',
  // className: '其它待定班级',
  // className: '',
  classId: '',
  // cov19: 0,
  isSmoke: 0,
  isSnore: 0,
  isGame: 0
})
const submitDis = ref(true)
const router = useRouter()
const classPopup = ref(null)
// 班级选择点击
const classClick = () => {
  classPopup.value.showClass = true
}
const setClass = obj => {
  className.value = obj.name
  form.value.classId = obj.id
}
// 用户特征
const other = ref([])
const changeOther = res => {
  form.value.isSmoke = 0
  form.value.isSnore = 0
  form.value.isGame = 0
  if (res.includes('isSmoke')) {
    form.value.isSmoke = 1
  }
  if (res.includes('isSnore')) {
    form.value.isSnore = 1
  }
  if (res.includes('isGame')) {
    form.value.isGame = 1
  }
  console.log(res)
}
// 身份证识别
const afterRead = async res => {
  const res2 = await getAccessToken(res.content)
  const cadeInfo = res2.words_result
  form.value.name = cadeInfo['姓名']?.words
  form.value.gender = cadeInfo['性别'].words === '女' ? 0 : 1
  form.value.ethnicity = cadeInfo['民族']?.words
  form.value.address = cadeInfo['住址']?.words
  form.value.birthday = cadeInfo['出生']?.words
  form.value.idNumber = cadeInfo['公民身份号码']?.words
}
// 用户头像上传
const avatarImg = ref([])
const uploadAvatar = res => {
  smallImg(res, 'avatar')
}

// 用户身份证上传
const cardImg = ref([])
const uploadCard = res => {
  smallImg(res, 'idCardImage')
}
// 压缩图片
const smallImg = (res, str) => {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  const img = new Image()
  img.src = res.content // 指定图片的DataURL(图片的base64编码数据)

  img.onload = () => {
    canvas.width = img.width
    canvas.height = img.height
    context.drawImage(img, 0, 0, canvas.width, canvas.height)
    if (res.file.size / 1024 > 100) {
      const baseUrl = canvas.toDataURL(res.file.type, 0.12)
      form.value[str] = baseUrl.substring(baseUrl.indexOf(',') + 1)
    } else {
      form.value[str] = res.content.substring(res.content.indexOf(',') + 1)
    }
  }
}
// 侦听身份证号
watch(
  () => form.value.idNumber,
  async (newVal, oldVal) => {
    await formCom.value.validate(['idNumber'])
    if (newVal === oldVal) {
      return
    }
    const res = await checkIdNumber(newVal)
    submitDis.value = true
    if (res.result.errno === 0 && res.result.data.step <= 5) {
      Dialog.alert({ message: '此人是入住状态，无法再次办理入住' }).then(() => {
        submitDis.value = false
        const {
          name,
          gender,
          ethnicity,
          idNumber,
          address,
          telephone,
          avatar,
          idCardImage,
          emergencyContact,
          emergencyContactTel,
          classId,
          isSmoke,
          isSnore,
          isGame
        } = res.result.data
        const birthday = res.result.data.birthday.split(' ')[0]
        form.value = {
          name,
          gender,
          birthday: birthday,
          ethnicity,
          idNumber,
          address,
          telephone,
          avatar,
          idCardImage,
          emergencyContact,
          emergencyContactTel,
          classId,
          isSmoke,
          isSnore,
          isGame
        }
        if (res.result.data.step === 1) {
          router.push('/guest?step=2&id=' + res.result.data.id)
        }
      })
    } else if (res.result.errno === 0 && res.result.data.step >= 6) {
      Dialog.alert({ message: '此人已办理退租，需要再次办理入住吗？' }).then(
        () => {
          submitDis.value = true
          const {
            name,
            gender,
            ethnicity,
            idNumber,
            address,
            telephone,
            avatar,
            idCardImage,
            emergencyContact,
            emergencyContactTel,
            classId,
            isSmoke,
            isSnore,
            isGame
          } = res.result.data
          const birthday = res.result.data.birthday.split(' ')[0]
          form.value = {
            name,
            gender,
            birthday: birthday,
            ethnicity,
            idNumber,
            address,
            telephone,
            avatar,
            idCardImage,
            emergencyContact,
            emergencyContactTel,
            classId,
            isSmoke,
            isSnore,
            isGame
          }

          // router.push('/reg?step=2&id=' + res.result.data.id)
        }
      )
    }
  },
  { deep: true }
)

// 提交
const formCom = ref(null)
const submit = async () => {
  await formCom.value.validate()
  if (!form.value.birthday.includes('-')) {
    form.value.birthday =
      form.value.birthday.substr(0, 4) +
      '-' +
      form.value.birthday.substr(4, 2) +
      '-' +
      form.value.birthday.substr(6, 2)
  }

  const res = await guestAdd(form.value)
  Toast.success('添加成功')
  router.push('/guest?step=2&id=' + res.result.data.guestId)
}
</script>

<style lang="scss" scoped>
.mb10 {
  margin-bottom: 10px;
}
.xk {
  padding: 15px;
  .title {
    margin-bottom: 10px;
  }
}
.tclass {
  font-size: 12px;
}
.btn {
  cursor: pointer;
  padding: 0 15px;
}
</style>
